<?php
header("Content-Type:text/html;charset=utf-8");

$content = file_get_contents("https://www.qbiqu.com/0_377/"); //读取该地址的数据

// var_dump($content);exit;
//匹配书籍名称

$namepreg = '/<div\s*id="info">.*<h1>(.*)<\/h1>.*<\/div>/imsU';
preg_match($namepreg, $content, $nameres);

var_dump($bookname);
exit;
//获取到书籍名称
$bookname = isset($nameres[1]) ? $nameres[1] : '';

if (empty($bookname)) {
  echo '书籍名为空';
  exit;
}


//匹配章节的正则
$chapter = "/<ul class=\"chapter-list clearfix\">(.*)<\/ul>/simU";

preg_match_all($chapter, $content, $chapterlist);

$booklist = isset($chapterlist[0][1]) ? $chapterlist[0][1] : '';

if (empty($booklist)) {
  echo '章节列表为空';
  exit;
}

//匹配链接部分
$chapter2 = "/<a.*href=\"(.*)\".*>(.*)<\/a>/imsU";

preg_match_all($chapter2, $booklist, $result);

// var_dump($result);
$UlrList = isset($result[1]) ? $result[1] : '';

$TitleList = isset($result[2]) ? $result[2] : '';
// var_dump($TitleList);

if (empty($UlrList) || empty($TitleList)) {
  echo '采集的列表为空';
  exit;
}

$ResultStr = '';

foreach ($UlrList as $key => $item) {
  //标题
  $ResultStr .= $TitleList[$key];

  $content = file_get_contents($item);
  if (empty($content)) {
    continue;
  }

  //匹配书籍的信息
  $infopreg = "/<div\s*class=\"bookinfo\"\s*>(.*)<\/div>/misU";
  preg_match($infopreg, $content, $infolist);


  $info = isset($infolist[1]) ? $infolist[1] : '';

  if (!empty($info)) {
    $authorpreg = "/<a\s*href=\".*\"\s*>(.*)<\/a>/";
    preg_match($authorpreg, $info, $author);
    $author = isset($author[1]) ? $author[1] : '';

    // //不为空就拼接
    if (!empty($author)) {
      // echo 111;exit;
      $ResultStr .= "\r\n\r\n作者：$author\r\n\r\n";
    }

    // //匹配更新时间
    $createpreg = "/更新时间.*<span>(.*)<\/span>/";
    preg_match($createpreg, $info, $time);
    $time = isset($time[1]) ? $time[1] : '';
    // var_dump($time);exit;
    // //逻辑短路
    if (!empty($time)) {
      $ResultStr .= "更新时间：$time\r\n\r\n";
    }
    // !empty($time) && $ResultStr .= "更新时间：$time";

  }
  $contentpreg = "/<div\s*class=\"content\".*>(.*)<\/div>/imsU";
  preg_match($contentpreg, $content, $article);
  $article = isset($article[1]) ? $article[1] : '';
  if (!empty($article)) {

    $article =  preg_replace('/<p.*?>|<\/p>/is', "\r\n\r\n", $article);
    $ResultStr .= $article . "\r\n\r\n";
  }
}
//写入
$filename = $bookname . ".txt";
$length = file_put_contents($filename, $ResultStr);


if ($length <= 0) {
  echo '采集失败';
} else {
  echo "采集结果为：$length 长度";
}
